# encoding: utf-8
"""
options.py

Created by Manel Rovira Trenc on 2008-06-01.
Copyright (c) 2008 __MyCompanyName__. All rights reserved.
"""

import sys
import os

from google.appengine.ext import db
import logging
import models




class Options(object):
    """docstring for Options"""
    def __init__(self):
        self._options = {}
        self._options.update(self.get_options())
        if len(self._options)==0:
            self.set_defaults()
    
    def set_defaults(self, initialize=True):
        """Create the default options"""
        self.new_option('blog_name', u'博客名称', 'str', 'Blog name')
        self.new_option('analytics', u'Google Analytics Keys', 'str', '')
        self.new_option('blog_desc', u'博客描述', 'str', 'Blog description')
        self.new_option('posts_per_page', u'文章每页显示个数', 'int', '5')
        self.new_option('posts_per_feed', u'feed每页显示个数', 'int', '10')
        self.new_option('DEBUG', 'Debug', 'boolean', 'False')
        self.new_option('CACHE', u'激活缓存', 'boolean', 'True')
        self.new_option('sidebar_widgets', 'Sidebar widgets', 'list', '["categories" ,"pages", "archives","links", "feed","tags","recentcomments"]','sidebar')
        self.new_option('permission', u'授权用户', 'list', '[]')
        self.new_option('theme', u'我的主题', 'select', 'default',"global",str(os.listdir('themes')))
        self.new_option('googlesearch', 'google search key', 'str', '003592794376351840562:7tbxmbyhyes')
#        self.new_option('tcss', 'css', 'str', 
#                        '''body{background-color:#FFFFFF;}
#
##layout{table-layout:fixed}
##layout td.c3t1{padding-left:10px;width:15%}
##layout td.c3t2{width:20px}
##layout td.c3t3{}
##layout td.c3t4{width:20px}
##layout td.c3t5{padding-right:10px;width:18%}
#
##header{width:100%;height:113px;background-color:#FFFFFF;border-left:1px solid #ccc;border-top:1px solid #ccc;border-right:1px solid #ccc;}
##header div.rc{}
##header div.tit{top:25px;left:20px;line-height:24px;font-size:22px;letter-spacing:4px;FONT-FAMILY: "宋体","Georgia","arial","sans-serif";}
##header div.tit a.titlink{font-weight:bold;text-decoration: none;color:#666;}
##header div.tit a.titlink:hover{color:#335588}
##header div.desc{top:50px;left:20px;padding-left:5px;padding-top:5px;font-size:14px;color:#999;FONT-FAMILY: "宋体","Georgia","arial","sans-serif";}
#
##tab{top:90px;background:#F0F0F0;border-top:1px solid #ccc;border-bottom:1px solid #ccc}
##tab a.on,#tab a.on:link,#tab a.on:visited{line-height:22px;color:#000;display:block;text-decoration:none;background:#ccc}
##tab span{color:#000000;font-size:12px;font-weight:bold}
##tab a:link{color:#000;text-decoration:none}
##tab a:visited{color:#000;text-decoration:none}
##tab a:hover{BACKGROUND:#ffffff;color:#ff6600;}
#
##tab2{background-color:#FFFFFF;border-left:1px solid #ccc;border-bottom:1px solid #ccc;border-right:1px solid #ccc;}
##tab2 span{color:#000000;font-size:12px;font-weight:bold}
##tab2 a{font-size:12px}
##tab2 a:link{color:#0000CC}
##tab2 a:visited{color:#0000CC}
#
#/*This CSS is created by dongbao: hi.baidu.com/dongbao/
#2006-06-23 22:31
#All rights Reservedh^_^*/
#
#.stage{background:#ffffff;font-color:#333333;border-left:1px solid #ccc;border-right:1px solid #ccc;}
#
##layout{margin-top:-10px}
##layout td.c1t1,#layout td.c2t3,#layout td.c3t1,#layout td.c3t3,#layout td.c3t5{padding-top:10px}
##layout td.c2t1{padding-top:10px;}
##layout td.c2t2{width:7px;border-left:1px dotted #000000}
##layout td.c2t3,#layout td.c3t5{background:#FFFFFF;}
#
##comm_info{color:#666666;font-family:Arial;text-align:left}
##comm_info div.line{margin-top:5px;line-height:8px;border-top:1px dotted #D6D6D6}
##comm_info a{color:#58a}
#
##page{height:30px;font-size:14px;font-family:Arial;text-align:center}
##page span{padding:3px;color:#000000;font-size:14px;font-weight:bold}
##page a.pc{color:#225C84;font-size:14px;font-weight:bold}
##page a.pc:visited{color:#225C84}
##page a.pi{padding:3px;color:#225C84;font-size:14px}
##page a.pi:visited{color:#225C84}
#
#.mod{margin-bottom:10px;border-bottom:1px dotted #D6D6D6}
#.modhandle{cursor:move}
#.modth{height:24px}
#.modhead{padding:4px 4px 0 4px}
#.modopt{padding:4px 4px 0 0}
#.modtit{color:#666;font-size:12px;font-weight:bold}a.modtit{color:#225C84}a.modtit:visited{color:#225C84}
#.modtitlink{color:#225C84;font-size:12px;font-weight:bold}a.modtitlink{color:#225C84;text-decoration:none}a.modtitlink:visited{color:#225C84;text-decoration:none}a.modtitlink:hover{color:#FF5100;text-decoration:underline}
#.modact{color:#225C84;font-size:12px}a.modact:link{color:#225C84}a.modact:visited{color:#225C84}
#.modbox{padding:10px 10px 0 10px}
#.modtl{line-height:1px}
#.modtc{}
#.modtr{line-height:1px}
#.modbl{line-height:1px}
#.modbc{line-height:1px}
#.modbr{line-height:1px}
#
##mod_mylink1 div.item{color:gray;font-size:12px}
##mod_mylink1 div.item a:link{color:#58a;font-size:12px;text-decoration:none}
##mod_mylink1 div.item a:hover{color:#cc6600;font-size:12px;text-decoration:underline;}
##mod_mylink1 div.item a:visited{color:#969;font-size:12px;text-decoration:none;}
##mod_mylink1 div.line{margin-top:5px;line-height:8px;border-top:1px dotted #D6D6D6}
#
##mod_mylink2 div.item{color:gray;font-size:12px}
##mod_mylink2 div.item a:link{color:#58a;font-size:12px;text-decoration:none}
##mod_mylink2 div.item a:hover{color:#cc6600;font-size:12px;text-decoration:underline;}
##mod_mylink2 div.item a:visited{color:#969;font-size:12px;text-decoration:none;}
##mod_mylink2 div.line{margin-top:5px;line-height:8px;border-top:1px dotted #D6D6D6}
#
##m_blog div.tit{font-size:14px;font-weight:bold}
##m_blog div.tit a{color:#cc6600;font-size:14px;font-weight:bold;text-decoration:none;background:url(http://hiphotos.baidu.com/dongbao/pic/item/e9eef01f923e56f5e0fe0b7c.jpg) repeat-x bottom;line-height:22px;target: (this.target='_blank');}
##m_blog div.tit a:hover{color:#666666;text-decoration:underline;background:none;}
##m_blog div.tit a:visited{color:#666666}
##m_blog div.date{margin:5px 0 8px 0;color:#666666;background-color:#F5F5F5;}
##m_blog div.cnt{color:#000000;line-height:20px;font-size:14px}
##m_blog div.more{margin:14px 0 16px 0}
##m_blog div.more a{color:#58a;font-size:14px}
##m_blog div.more a:hover{color:#cc6600;text-decoration:underline;}
##m_blog div.more a:visited{color:#969}
##m_blog div.opt{color:#666666;font-size:12px}
##m_blog div.opt a:link{color:#58a;font-size:12px;text-decoration:none;}
##m_blog div.opt a:hover{color:#cc6600;text-decoration:underline;}
##m_blog div.opt a:visited{color:#969;text-decoration:none;}
##m_blog div.line{margin-top:17px;line-height:17px;border-top:1px dotted #D6D6D6}
##m_blog div.none{padding:100px 0 100px 0;color:#000000;font-size:14px}
#
##m_pro a:link{color:#58a;text-decoration:none;}
##m_pro a:hover{color:#cc6600;text-decoration:underline;}
##m_pro a:visited{color:#969;text-decoration:none;}
##m_pro div.image{text-align:center}
##m_pro div.act{margin-top:10px}
##m_pro div.user{margin-top:10px;color:#666666;font-size:12px;font-weight:bold}
##m_pro div.desc{color:#666666;font-size:12px}
##m_pro div.line{margin-top:17px;line-height:17px;border-top:1px dotted #D6D6D6}
##m_pro td{color:#666666;line-height:24px;font-size:14px}
#
##m_links div.item{color:gray;font-size:12px}
##m_links div.item a:link{color:#58a;font-size:12px;text-decoration:none}
##m_links div.item a:hover{color:#cc6600;font-size:12px;text-decoration:underline;}
##m_links div.item a:visited{color:#969;font-size:12px;text-decoration:none;}
##m_links div.line{margin-top:5px;line-height:8px;border-top:1px dotted #D6D6D6}
#
##m_artclg div.item{color:gray;font-size:12px}
##m_artclg div.item a:link{color:#58a;font-size:12px;text-decoration:none}
##m_artclg div.item a:hover{color:#cc6600;font-size:12px;text-decoration:underline;}
##m_artclg div.item a:visited{color:#969;font-size:12px;text-decoration:none;}
##m_artclg div.line{margin-top:5px;line-height:8px;border-top:1px dotted #D6D6D6}
#
##m_filed div.item{color:gray;font-size:12px}
##m_filed div.item a:link{color:#58a;font-size:12px;text-decoration:none}
##m_filed div.item a:hover{color:#cc6600;font-size:12px;text-decoration:underline;}
##m_filed div.item a:visited{color:#969;font-size:12px;text-decoration:none;}
##m_filed div.line{margin-top:5px;line-height:8px;border-top:1px dotted #D6D6D6}
#
##m_comment div.item{color:#gray;font-size:12px}
##m_comment div.item a:link{color:#58a;font-size:12px;text-decoration:none}
##m_comment div.item a:hover{color:#cc6600;font-size:12px;text-decoration:underline;}
##m_comment div.item a:visited{color:#969;font-size:12px;text-decoration:none;}
##m_comment div.item a.cnt:link{color:#58a;font-size:12px;text-decoration:none}
##m_comment div.item a.cnt:hover{color:#cc6600;font-size:12px;text-decoration:underline;}
##m_comment div.item a.cnt:visited{color:#969;font-size:12px;text-decoration:none;}
##m_comment div.line{margin-top:5px;line-height:8px;border-top:1px dotted #D6D6D6}
#
##m_sysinfo a{color:#225C84}
##m_sysinfo a:visited{color:#225C84}
##m_sysinfo{line-height:22px;color:#666666;font-size:14px}
##m_sysinfo span.new{color:#FF0000;font-size:10px;font-family:Arial}
##m_sysinfo span.date{color:#666666;font-size:14px}
#
##m_setbase{color:#666666;font-size:14px}
##m_setbase td{color:#666666;font-size:14px}
##m_setbase div.line{margin-top:5px;line-height:8px;border-top:1px dotted #D6D6D6}
#
##in_comment{width:710px}
##in_comment div.tit{margin-bottom:12px;color:#666666;font-size:14px;font-weight:bold}
##in_comment div.user{margin-bottom:6px;color:#666666;font-size:12px}
##in_comment div.user a{color:#225C84;font-size:12px}
##in_comment div.user a:visited{color:#225C84}
##in_comment div.user span.date{color:#666666;font-size:12px}
##in_comment div.desc{color:#666666;font-size:12px}
##in_comment div.line{margin-top:17px;line-height:17px;border-top:1px dotted #D6D6D6}
#
##in_send div.tit{margin:10px 0 10px 0;color:#666666;font-size:14px;font-weight:bold}'''.replace("\r","").replace("\n",""), "global", '')
        if initialize:
             functions = __import__('functions')
             functions.init_blog()
            
        
    def get_options(self):
        """Read the options from the datastore and return a dict of options"""
        opts = models.Option.all()
        items = {}
        for opt in opts:
            items.update({opt.name: {'value': self.get_value(opt),
                                       'type': opt.option_type}
                          })
        return items
       
    def get_value(self, opt):
        """Get the value of the options"""
        if not opt.value:
            return None
        elif opt.option_type=="int":
            return int(opt.value)
        elif opt.option_type=="str":
            return opt.value
        elif opt.option_type=="boolean":
            if opt.value == 'True':
                return True
            else:
                return False
        elif opt.option_type=="list":
            try:
                list = eval(opt.value)
            except:
                return []
            if type(list) == type([]):
                return list
            else: 
                return []
        elif opt.option_type=="select":
            return opt.value
    
    def check(self, value, opt_type):
        """Check if option value are valid for the option type given"""
        if opt_type == 'boolean':
            if value == 'True' or value == 'False':
                return
            return 'Invalid boolean value'
        elif opt_type == 'int':
            try:
                res = int(value)
            except:
                return 'Invalid integer'
            return
        elif opt_type == "list":
            err=''
            try:
                alist = eval(value)
            except:
                return 'Invalid data format'
            if type(alist) == type([]):
                return
            else: 
                return 'Invalid data format'
        return 
      
    def set_option(self, name, value):
        """Set the option for a option"""  
        imp_models = __import__('models')
        imp_logging = __import__('logging')
        #imp_logging.error('%s %s' % (type(imp_models), type(models)))
        opt = imp_models.Option.all().filter('name',name).get()
        if not opt:
            return {'Error': 'Option not found'}
        if not value:
            opt.value = None
        else:
            err = self.check(value, opt.option_type)
            if err:
                return {opt.label: err}                 
            else:
                opt.value = value
        try:
            opt.put()
        except:
            return {'Error': 'Error saving option'}
        self._options.update({name: {'value':self.get_value(opt), 'type':opt.option_type} })
        return {}
    
    def new_option(self, name, label, option_type, value=None, space="global",selected=''):
        """Create a new option in the datastore"""
        if not self._options.has_key(name):
            opt = models.Option(name=name, label=label, option_type=option_type, space=space,selected_value=selected)
            if value:
                opt.value = value
            opt.put()
            self._options.update({name: {'value':self.get_value(opt), 'type':opt.option_type} })
    
    def options_list(self):
        """Return a list whith the options names"""
        return self._options.keys()   
        
    def __getattribute__(self, name):
        try:
            return object.__getattribute__(self,name)
        except AttributeError:
            dict = object.__getattribute__(self,'_options')
            if name=='dict':
                return dict
            if dict.has_key(name):
                return dict[name]['value']
            else:
                raise AttributeError

BLOGSITES ='http://www.woiclub.cn'
MIDDLEWARE_CLASSES = (
#        'middleware.requestCounters.RequestMiddleware',
)

TIME_ZONE = 'Asia/beijing'

TIME = 8 


LANGUAGE_CODE = 'zh_cn'

SECRET_KEY = 'hvhxfm5u=^*v&doo#oq8x*eg8+1&9sxbye@=umutgn^t_sg_nx'
